home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9441 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: malloc question
  5. Date: 10 Mar 1996 10:18:06 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4hv6cuINNpi0@keats.ugrad.cs.ubc.ca>
  8. References: <4htonk$350@news.hklink.net> <4hv45e$svm@inet-nntp-gw-1.us.oracle.com>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4hv45e$svm@inet-nntp-gw-1.us.oracle.com>,
  12. William Kaufman <wkaufman@wkaufman.us.oracle.com> wrote:
  13.  >In article <4htonk$350@news.hklink.net> alex@station.net (Alex Chu) writes:
  14.  >] 
  15.  >] main()
  16.  >] {
  17.  >]   PITEM head, current;
  18.  >]   head=(PITEM) malloc(sizeof(ITEM));
  19.  >]             ^^^^^^^
  20.  >]   head->val=1;
  21.  >] }
  22.  >] 
  23.  >] I want to know why need to use the type casting PITEM in front of the
  24.  >] malloc ?  Please help!
  25.  >
  26.  >    Either:
  27.  >
  28.  >    a) you're using a pre-ANSI compiler which complains that you can't
  29.  >portably cast from (char *) to (PITEM) (in which case, you could go and
  30.  >get an ANSI compiler); or,
  31.  >
  32.  >    b) you aren't including <stdlib.h>, where malloc() is defined as
  33.  >returning (void *), and the compiler thinks it returns (int).
  34.  
  35. Which is a serious error that summons undefined behavior.  Never mind that the
  36. mapping function from integral types to pointers is implementation defined;
  37. never mind that there is a possible disparity between the size of an int and a
  38. pointer---these issues don't even enter into it. An int return value may not
  39. even be passed back _in the same register_ as a pointer return value! This is
  40. simply a case of calling a function that is declared one way, and defined
  41. another way, cast or no cast.
  42.  
  43. If I were implementing a C compiler for, say, a 680x0 architecture, I might use
  44. the A0 register for returning pointers, and D0 for returning integers, just
  45. because it is more convenient for the caller to have a pointer ready in an
  46. address register and an integer ready in a data register. 
  47.  
  48. The fact that a function call which has an incompatible declaration (implicit
  49. or otherwise) with respect to the function definition is undefiend would allow
  50. me that implementational latitude.
  51. -- 
  52.  
  53.